package com.alex.tinyurl.service;

import com.alex.tinyurl.api.ITinyUrl;
import com.alex.tinyurl.service.genstrategy.TinyUrlGenerateStrategy;
import com.alex.tinyurl.service.store.UrlMappingStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Optional;

@Service(value = "tinyUrlService")
public class TinyUrlService implements ITinyUrl {

    private final static Logger LOG = LoggerFactory.getLogger(TinyUrlService.class);
    @Resource
    private UrlMappingStore mappingStore;
    @Resource
    private TinyUrlGenerateStrategy tinyUrlGenerateStrategy;

    @Override
    public String genUrl(String originalUrl) {
        Optional<String> savedTinyUrl = mappingStore.getTinyUrl(originalUrl);
        if (savedTinyUrl.isPresent()) {
            return savedTinyUrl.get();
        }
        String tinyUrl = tinyUrlGenerateStrategy.generateTinyUrl(originalUrl);
        mappingStore.saveUrlMap(tinyUrl, originalUrl);
        return tinyUrl;
    }

    @Override
    public String getOriginalUrl(String tinyUrl) {
        Optional<String> originalUrl = mappingStore.getOriginalUrl(tinyUrl);
        if (!originalUrl.isPresent()) {
            return "";
        }
        return originalUrl.get();
    }
}
